<?php defined('BASEPATH') OR exit('No direct script access allowed');

class series extends Services{
	private $status = true;
	
	function series(){
		parent::__construct();
	}
	
	/**
	 * Agregar series
	 */
	public function add(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('add');
		if($this->status == true){
			$this->load->model('series_model');
			$data = $this->series_model->addSerie(self::$params);
			
			return $this->parseOutput($data);
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	/**
	 * Modificar una serie
	 */
	public function update(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('update');
		if($this->status == true){
			$this->load->model('series_model');
			$data = $this->series_model->updateSerie(self::$params);
			
			return $this->parseOutput($data);
		}else
			throw new UserValidateException(implode(',',$response_errors));
	
	}
	
	/**
	 * Agregar una temporada a una serie
	 */
	public function add_season(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('add_season');
		if($this->status == true){
			$this->load->model('series_model');
			$data = $this->series_model->addSeason(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
			
			if($data==1)
				throw new NotExistException('serie');
			else
				throw new ImageNotFoundException();
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	/**
	 * Modificar una temporada a una serie
	 */
	public function update_season(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('update_season');
		if($this->status == true){
			$this->load->model('series_model');
			$data = $this->series_model->updateSeason(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
			
			if($data == 1)
				throw new NotExistException('serie');
			else
				throw new NotExistException('season');
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	/**
	 * Obtiene la informacion de una temporada
	 */
	public function get_season(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('get_season');
		if($this->status == true){
			$this->load->model('series_model');
			$data = $this->series_model->getSeason(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
			else
				throw new NotExistException('season');
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	/**
	 * Agregar un capitulo a una temporada de una serie
	 */
	public function add_episode(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('add_episode');
		if($this->status == true){
			$this->load->model('series_model');
			$data = $this->series_model->addEpisode(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
			
			if($data==1)
				throw new NotExistException('season');
			else
				throw new ImageNotFoundException();
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	/**
	 * Modificar un capitulo de una temporada de una serie
	 */
	public function update_episode(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('update_episode');
		if($this->status == true){
			$this->load->model('series_model');
			$data = $this->series_model->updateEpisode(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
			
			if($data == 1)
				throw new NotExistException('season');
			else
				throw new NotExistException('episode');
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}

	/**
	 * Obtiene la informacion de un capitulo
	 */
	public function get_episode(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('get_episode');
		if($this->status == true){
			$this->load->model('series_model');
			$data = $this->series_model->getEpisode(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
			else
				throw new NotExistException('episode');
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	
	
	/**
	 * ]]]]]]]] METODOS DE THETVDB
	 * 
	 * Busca series espesificando el nombre
	 */
	public function tvdb_search(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('tvdb_search');
		if($this->status == true){
			$this->load->model('series_model');
			$data = $this->series_model->tvdbSearch(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
			else
				throw new NotExistException('episode');
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	/**
	 * Obtiene la informacion de una serie
	 */
	public function tvdb_serie(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('tvdb_serie');
		if($this->status == true){
			$this->load->model('series_model');
			$data = $this->series_model->tvdbSerie(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
			else
				throw new NotExistException('tvdb_id');
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	/**
	 * Obtiene la informacion de un capitulo de una serie
	 */
	public function tvdb_episode(){
		$this->checkAccessToken();
		
		$response_errors = $this->validate('tvdb_episode');
		if($this->status == true){
			$this->load->model('series_model');
			$data = $this->series_model->tvdbEpisode(self::$params);
			if(is_array($data))
				return $this->parseOutput($data);
			else
				throw new NotExistException('tvdb_id');
		}else
			throw new UserValidateException(implode(',',$response_errors));
	}
	
	
	
	
	/**
     * Permite incorporar las validaciones bases que apliquen para todos los servicios.
     * Validaciones mas espesificas tendran que ser en cada servicio en particular.
     * @author gama
     */
    private function validate($val_method){
    	if(method_exists($this, 'validate_'.$val_method)){
    		$this->load->library('MY_Form_validation');
    		return $this->{'validate_'.$val_method}();
    	}
    }
    
	private function validate_add(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'title', 
                     'label' => 'title', 
                     'rules' => 'required|max_length[100]'),
				array('field' => 'date_release', 
                     'label' => 'date_release', 
                     'rules' => 'required'),
				array('field' => 'cast[]', 
                     'label' => 'cast[]', 
                     'rules' => 'is_natural_no_zero'),
				array('field' => 'categories[]', 
                     'label' => 'categories[]', 
                     'rules' => 'is_natural_no_zero')
    	));
		$this->status = $validate->run();
		
		$fecha = new Fecha();
		if(isset(self::$params['date_release'])){
			if(!$fecha->is_date(self::$params['date_release'])){
				$this->status = FALSE;
				$validate->_error_array['date_release'] = lang('txt_invalid_date').' (date_release)';
			}
		}
		
		
    	return $validate->_error_array;
    }

	private function validate_update(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'serie', 
                     'label' => 'serie', 
                     'rules' => 'required|is_natural_no_zero'),
    			array('field' => 'title', 
                     'label' => 'title', 
                     'rules' => 'required|max_length[100]'),
				array('field' => 'date_release', 
                     'label' => 'date_release', 
                     'rules' => 'required'),
				array('field' => 'cast[]', 
                     'label' => 'cast[]', 
                     'rules' => 'is_natural_no_zero'),
				array('field' => 'categories[]', 
                     'label' => 'categories[]', 
                     'rules' => 'is_natural_no_zero')
    	));
		$this->status = $validate->run();
		
		$fecha = new Fecha();
		if(isset(self::$params['date_release'])){
			if(!$fecha->is_date(self::$params['date_release'])){
				$this->status = FALSE;
				$validate->_error_array['date_release'] = lang('txt_invalid_date').' (date_release)';
			}
		}
		
		
    	return $validate->_error_array;
    }

	private function validate_add_season(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
		$valida_poster = array();
		if(!isset($_FILES['poster']['name']) && !isset(self::$params['poster'])){
			$valida_poster = array(
				'field' => 'poster', 
				'label' => 'poster', 
				'rules' => 'required');
		}
    	$validate->set_rules(array(
    			array('field' => 'serie', 
                     'label' => 'serie', 
                     'rules' => 'required|is_natural_no_zero'),
    			array('field' => 'no_season', 
                     'label' => 'no_season', 
                     'rules' => 'required|is_natural'),
				array('field' => 'date_release', 
                     'label' => 'date_release', 
                     'rules' => 'required'),
                $valida_poster,
				array('field' => 'trailers', 
                     'label' => 'trailers', 
                     'rules' => 'alpha_numeric'),
				array('field' => 'coming_soon', 
                     'label' => 'coming_soon', 
                     'rules' => 'expression:/^(0|1)$/')
    	));
		$this->status = $validate->run();
		
		$fecha = new Fecha();
		if(isset(self::$params['date_release'])){
			if(!$fecha->is_date(self::$params['date_release'])){
				$this->status = FALSE;
				$validate->_error_array['date_release'] = lang('txt_invalid_date').' (date_release)';
			}
		}
		
		if(isset(self::$params['poster'])){
			if(Sys::urlValid(self::$params['poster']) == FALSE){
				$this->status = FALSE;
				$validate->_error_array['poster'] = lang('txt_invalid_url', 'poster');
			}
		}
		
    	return $validate->_error_array;
    }

	private function validate_update_season(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'season', 
                     'label' => 'season', 
                     'rules' => 'required|is_natural_no_zero'),
    			array('field' => 'serie', 
                     'label' => 'serie', 
                     'rules' => 'required|is_natural_no_zero'),
    			array('field' => 'no_season', 
                     'label' => 'no_season', 
                     'rules' => 'is_natural'),
				array('field' => 'trailers', 
                     'label' => 'trailers', 
                     'rules' => 'alpha_numeric'),
				array('field' => 'coming_soon', 
                     'label' => 'coming_soon', 
                     'rules' => 'expression:/^(0|1)$/')
    	));
		$this->status = $validate->run();
		
		$fecha = new Fecha();
		if(isset(self::$params['date_release'])){
			if(!$fecha->is_date(self::$params['date_release'])){
				$this->status = FALSE;
				$validate->_error_array['date_release'] = lang('txt_invalid_date').' (date_release)';
			}
		}
		
		if(isset(self::$params['poster'])){
			if(Sys::urlValid(self::$params['poster']) == FALSE){
				$this->status = FALSE;
				$validate->_error_array['poster'] = lang('txt_invalid_url', 'poster');
			}
		}
		
    	return $validate->_error_array;
    }

	private function validate_add_episode(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'season', 
                     'label' => 'season', 
                     'rules' => 'required|is_natural_no_zero'),
    			array('field' => 'no_episode', 
                     'label' => 'no_episode', 
                     'rules' => 'required|is_natural'),
				array('field' => 'title', 
                     'label' => 'title', 
                     'rules' => 'required|max_length[100]'),
                     
				array('field' => 'format_episode', 
                     'label' => 'format_episode', 
                     'rules' => 'max_length[10]'),
				array('field' => 'quality', 
                     'label' => 'quality', 
                     'rules' => 'max_length[20]'),
				array('field' => 'duration', 
                     'label' => 'duration', 
                     'rules' => 'max_length[30]'),
				array('field' => 'size', 
                     'label' => 'size', 
                     'rules' => 'max_length[20]'),
				array('field' => 'languaje', 
                     'label' => 'languaje', 
                     'rules' => 'max_length[20]'),
				array('field' => 'subtitles', 
                     'label' => 'subtitles', 
                     'rules' => 'max_length[20]'),
				array('field' => 'sinopsis_spa', 
                     'label' => 'sinopsis_spa', 
                     'rules' => 'max_length[10000]'),
				array('field' => 'sinopsis_eng', 
                     'label' => 'sinopsis_eng', 
                     'rules' => 'max_length[10000]'),
				array('field' => 'servers[]', 
                     'label' => 'servers[]', 
                     'rules' => 'max_length[100]'),
				array('field' => 'sources[]', 
                     'label' => 'sources[]', 
                     'rules' => 'max_length[150]'),
				array('field' => 'online[]', 
                     'label' => 'online[]', 
                     'rules' => 'max_length[1]|is_natural'),
				array('field' => 'date_release', 
                     'label' => 'date_release', 
                     'rules' => 'max_length[10]')
    	));
		$this->status = $validate->run();
		
		if(isset(self::$params['screenshots'])){
			if(Sys::urlValid(self::$params['screenshots']) == FALSE){
				$this->status = FALSE;
				$validate->_error_array['screenshots'] = lang('txt_invalid_url', 'screenshots');
			}
		}
		
		if(isset(self::$params["servers"]) && isset(self::$params['sources']) && isset(self::$params["online"])){
			if(count(self::$params["servers"]) != count(self::$params["sources"]) 
				|| count(self::$params["servers"]) != count(self::$params["online"])){
				$this->status = FALSE;
				$validate->_error_array['values'] = lang('txt_missing_params','servers[]','sources[]', 'online[]');
			}
			
			if($this->status)
				foreach (self::$params["sources"] as $key => $itm)
					if(!sys::urlValid($itm)){
						$this->status = FALSE;
						$validate->_error_array['values'] = lang('txt_invalid_url', 'sources => "'.$itm.'"');
					}
		}
		
		//	VALIDA QUE LA FECHA DATE_RELEASE SEA VALIDA.
		$fecha = new Fecha();
		if(isset(self::$params['date_release'])){
			if(!$fecha->is_date(self::$params['date_release'])){
				$this->status = FALSE;
				$validate->_error_array['date_release'] = lang('txt_invalid_date').' (date_release)';
			}
		}
		
    	return $validate->_error_array;
    }

	private function validate_update_episode(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'season', 
                     'label' => 'season', 
                     'rules' => 'required|is_natural_no_zero'),
                 array('field' => 'episode', 
	                 'label' => 'episode', 
	                 'rules' => 'required|is_natural_no_zero'),
    			
    			array('field' => 'no_episode', 
                     'label' => 'no_episode', 
                     'rules' => 'is_natural'),
				array('field' => 'title', 
                     'label' => 'title', 
                     'rules' => 'max_length[100]'),
				array('field' => 'format_episode', 
                     'label' => 'format_episode', 
                     'rules' => 'max_length[10]'),
				array('field' => 'quality', 
                     'label' => 'quality', 
                     'rules' => 'max_length[20]'),
				array('field' => 'duration', 
                     'label' => 'duration', 
                     'rules' => 'max_length[30]'),
				array('field' => 'size', 
                     'label' => 'size', 
                     'rules' => 'max_length[20]'),
				array('field' => 'languaje', 
                     'label' => 'languaje', 
                     'rules' => 'max_length[20]'),
				array('field' => 'subtitles', 
                     'label' => 'subtitles', 
                     'rules' => 'max_length[20]'),
				array('field' => 'sinopsis_spa', 
                     'label' => 'sinopsis_spa', 
                     'rules' => 'max_length[10000]'),
				array('field' => 'sinopsis_eng', 
                     'label' => 'sinopsis_eng', 
                     'rules' => 'max_length[10000]'),
				array('field' => 'servers[]', 
                     'label' => 'servers[]', 
                     'rules' => 'max_length[100]'),
				array('field' => 'sources[]', 
                     'label' => 'sources[]', 
                     'rules' => 'max_length[150]'),
				array('field' => 'online[]', 
                     'label' => 'online[]', 
                     'rules' => 'max_length[1]|is_natural'),
				array('field' => 'date_release', 
                     'label' => 'date_release', 
                     'rules' => 'max_length[10]')
    	));
		$this->status = $validate->run();
		
		if(isset(self::$params['screenshots'])){
			if(Sys::urlValid(self::$params['screenshots']) == FALSE){
				$this->status = FALSE;
				$validate->_error_array['screenshots'] = lang('txt_invalid_url', 'screenshots');
			}
		}
		
		if(isset(self::$params["servers"]) && isset(self::$params['sources']) && isset(self::$params["online"])){
			if(count(self::$params["servers"]) != count(self::$params["sources"])
				|| count(self::$params["servers"]) != count(self::$params["online"])){
				$this->status = FALSE;
				$validate->_error_array['values'] = lang('txt_missing_params','servers[]','sources[]', 'online[]');
			}
			
			if($this->status)
				foreach (self::$params["sources"] as $key => $itm)
					if(!sys::urlValid($itm)){
						$this->status = FALSE;
						$validate->_error_array['values'] = lang('txt_invalid_url', 'sources => "'.$itm.'"');
					}
		}
		
		//	VALIDA QUE LA FECHA DATE_RELEASE SEA VALIDA.
		$fecha = new Fecha();
		if(isset(self::$params['date_release'])){
			if(!$fecha->is_date(self::$params['date_release'])){
				$this->status = FALSE;
				$validate->_error_array['date_release'] = lang('txt_invalid_date').' (date_release)';
			}
		}
    	return $validate->_error_array;
    }
    
    private function validate_get_episode(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'episode', 
                     'label' => 'episode', 
                     'rules' => 'required|is_natural_no_zero')
    	));
		$this->status = $validate->run();
		return $validate->_error_array;
    }
	
	private function validate_get_season(){
    	$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'season', 
                     'label' => 'season', 
                     'rules' => 'required|is_natural_no_zero')
    	));
		$this->status = $validate->run();
		return $validate->_error_array;
    }
	
	
	
	private function validate_tvdb_search(){
		$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'title', 
                     'label' => 'title', 
                     'rules' => 'required|max_length[100]')
    	));
		$this->status = $validate->run();
		return $validate->_error_array;
	}
	
	private function validate_tvdb_serie(){
		$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'tvdb_id', 
                     'label' => 'tvdb_id', 
                     'rules' => 'required|is_natural_no_zero')
    	));
		$this->status = $validate->run();
		return $validate->_error_array;
	}
	
	private function validate_tvdb_episode(){
		$validate = new MY_Form_validation();
    	$validate->setArrayValidate(self::$params);
    	
    	$validate->set_rules(array(
    			array('field' => 'tvdb_id', 
                     'label' => 'tvdb_id', 
                     'rules' => 'required|is_natural_no_zero'),
				array('field' => 'season', 
                     'label' => 'season', 
                     'rules' => 'required|is_natural_no_zero'),
				array('field' => 'episode', 
                     'label' => 'episode', 
                     'rules' => 'required|is_natural_no_zero')
    	));
		$this->status = $validate->run();
		return $validate->_error_array;
	}
	
    
    
    
	private function parseOutput($data=array(), $only_parse=false){
		if ($only_parse)
			return $this->{'_format_'.$this->getFormat()}($data);
		if($this->status==true){
			return $this->{'_trim_format_'.$this->getFormat()}(
					$this->{'_format_'.$this->getFormat()}($data)
					);
		}
    }
}